package com.suning.sawp.web.controller;

import java.security.Principal;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.constants.PromotionConstants;
import com.suning.sawp.constants.PromotionErrorConstants;
import com.suning.sawp.dto.aircondition.CouponReq;
import com.suning.sawp.dto.aircondition.ValidActivityIdReq;
import com.suning.sawp.dto.common.MyQueryParam;
import com.suning.sawp.dto.common.QueryResult;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.precharge.CommonRtn;
import com.suning.sawp.dto.promotion.ActivityDetailInfo;
import com.suning.sawp.dto.promotion.CouponCommInfo;
import com.suning.sawp.dto.promotion.CouponRecordBean;
import com.suning.sawp.dto.promotion.InnerCouponDetail;
import com.suning.sawp.dto.promotion.QueryActBean;
import com.suning.sawp.intf.promotion.PromotionActivityService;
import com.suning.sawp.web.exception.MyGsonView;

/**
 * 
 * 促销中心活动查询controller<br>
 * 〈功能详细描述〉
 * 
 * @author Wuxiao
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/coupon")
public class PromotionActivityController extends DjBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_SERVICE);

    @Autowired
    PromotionActivityService    promotionActivityService;

    /**
     * 
     * 功能描述:查询促销活动列表 <br>
     * 〈功能详细描述〉
     * 
     * @param type
     * @param cityId
     * @param couponResource
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryActivityList.do")
    public MyGsonView queryActivity(String type, String cityId,Integer couponResource, Principal principal) {
        String userId = principal.getName();
        LOGGER.debug("queryActivityList, userId=" + userId + ", type=" + type + ", cityId="
                + cityId);
        ReturnMsg<List<QueryActBean>> ret = new ReturnMsg<List<QueryActBean>>();
        try {
            ret = promotionActivityService.queryActivity(type, cityId, userId,couponResource);
        } catch (Exception e) {
            ret.setRetFlag(ReturnMsg.FAIL);
            ret.setErrorCode(PromotionErrorConstants.ACT_QUERY_ERR_E999);
            ret.setErrorMessage(PromotionErrorConstants.ACT_QUERY_ERR_MAP
                    .get(PromotionErrorConstants.ACT_QUERY_ERR_E999));
            LOGGER.error("queryActivityList.do ERROR", e);
        }
        return setGsonView(ret);
    }
    
    
    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param type
     * @param cityId
     * @param couponResource
     * @param principal
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryActivityListNew.do")
    public MyGsonView queryActivityListNew(String type, String cityId,Integer couponResource, Principal principal) {
        String userId = principal.getName();
        LOGGER.info("queryActivityList, userId=" + userId + ", type=" + type + ", cityId="
                + cityId);
        ReturnMsg<List<QueryActBean>> ret = new ReturnMsg<List<QueryActBean>>();
        try {
            ret = promotionActivityService.queryActivityListNew(type, cityId, userId,couponResource);
        } catch (Exception e) {
            ret.setRetFlag(ReturnMsg.FAIL);
            ret.setErrorCode(PromotionErrorConstants.ACT_QUERY_ERR_E999);
            ret.setErrorMessage(PromotionErrorConstants.ACT_QUERY_ERR_MAP
                    .get(PromotionErrorConstants.ACT_QUERY_ERR_E999));
            LOGGER.error("queryActivityListNew.do ERROR", e);
        }
        return setGsonView(ret);
    }

    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     * 
     * @param currIndex 当前索引
     * @param pageSize 页面大小
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryPerformList.do")
    public MyGsonView queryCouponRecord(
            @RequestParam(value = "currIndex", required = false) int currIndex,
            @RequestParam(value = "pageSize", required = false) int pageSize, Principal principal) {
        // 获取当前用户id，即工号
        String userId = principal.getName();

        LOGGER.debug("queryCouponRecordList, userId=" + userId + ", currIndex=" + currIndex
                + ", pageSize=" + pageSize);

        // 构造分页查询参数
        MyQueryParam<String> param = new MyQueryParam<String>();
        param.setQueryParam(userId);
        param.setCurrIndex(Integer.valueOf(currIndex));
        param.setPageSize(Integer.valueOf(pageSize));

        // 定义数据列表
        QueryResult<CouponRecordBean> result = null;
        try {

            // 调用业务接口查询业务数据列表分页信息
            result = promotionActivityService.queryCouponRecord(param);

        } catch (Exception e) {
            LOGGER.warn("queryCouponRecord failed", e);
        }

        MyGsonView view = createGsonView();
        view.addStaticAttribute("data", result);
        // 转换实体为json字符串返回
        return view;
    }

    /**
     * 
     * 功能描述:确认发券接口<br>
     * 〈功能详细描述〉
     * 
     * @param activityId 活动Id
     * @param mobile 手机号
     * @param principal
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping({ "/perform.do" })
    public MyGsonView sendCoupon(String activityId, String mobile,String storeCode, Principal principal) {
        String userId = principal.getName();
        LOGGER.debug("sendCoupon, userId=" + userId + ", activityId=" + activityId + ", mobile="
                + mobile + ",storeCode=" + storeCode);
        ReturnMsg<CommonRtn> ret = new ReturnMsg<CommonRtn>();
        try {
            ret = promotionActivityService.sendCoupon(activityId, mobile, userId, storeCode);
        } catch (Exception e) {
            ret.setRetFlag(ReturnMsg.FAIL);
            ret.setErrorCode(PromotionErrorConstants.COUPON_SEND_ERR_E999);
            ret.setErrorMessage(PromotionErrorConstants.COUPON_SEND_ERR_MAP
                    .get(PromotionErrorConstants.COUPON_SEND_ERR_E999));
            LOGGER.error(String.format("PromotionActivityController.sendCoupon error:activityId=%s,mobile=%s,storeCode=%s,userId=%s", activityId,mobile,storeCode,userId),e);
        }
        return setGsonView(ret);
    }

    /**
     * 查询活动详情
     * 
     * @param activityId
     * @param activityName
     * @param cityId
     * @param endTime
     * @param mobile
     * @param securityKey
     * @param startTime
     * @return
     */
    @RequestMapping("/queryActivityDetail.do")
    public MyGsonView queryActivityDetail(String activityId,String mobile,Principal principal) {
        // 获取当前用户id，即工号
        String userId = principal.getName();
        LOGGER.debug("开始查询活动详情, activityId=" + activityId + ",mobile=" + mobile + ",userId=" + userId);
        ReturnMsg<ActivityDetailInfo> ret = new ReturnMsg<ActivityDetailInfo>();
        if (StringUtils.isEmpty(activityId) || StringUtils.isEmpty(mobile)) {
            ret.setRetFlag(ReturnMsg.FAIL);
            ret.setErrorCode(PromotionErrorConstants.COUPON_QUERY_ERR_E001);
            ret.setErrorMessage(PromotionErrorConstants.COUPON_QUERY_ERR_MAP
                    .get(PromotionErrorConstants.COUPON_QUERY_ERR_E001));
            return setGsonView(ret);
        }
        try {
            ret = promotionActivityService.queryActivityDetail(activityId, mobile, userId);
        } catch (Exception e) {
            Object[] errArgs = { activityId,mobile,userId, e };
            LOGGER.error("查询活动详情失败，activityId:{},mobile:{},userId:{}, error:{}",
                    errArgs);
            ret.setRetFlag(ReturnMsg.FAIL);
            ret.setErrorCode(PromotionErrorConstants.COUPON_QUERY_ERR_E999);
            ret.setErrorMessage(PromotionErrorConstants.COUPON_QUERY_ERR_MAP
                    .get(PromotionErrorConstants.COUPON_QUERY_ERR_E999));
        }
        return setGsonView(ret);
    }
    
    
    @RequestMapping("/queryActivityDetailNew.do")
    public MyGsonView queryActivityDetailNew(String activityId,String couponRuleCode,Principal principal) {
        // 获取当前用户id，即工号
        String userId = principal.getName();
        LOGGER.info("queryActivityDetailNew , 开始查询活动详情, couponRuleCode=" + couponRuleCode  + ",userId=" + userId);
        ReturnMsg<ActivityDetailInfo> ret = new ReturnMsg<ActivityDetailInfo>();
        if (StringUtils.isEmpty(couponRuleCode) || StringUtils.isEmpty(activityId)) {
            ret.setRetFlag(ReturnMsg.FAIL);
            ret.setErrorCode(PromotionErrorConstants.COUPON_QUERY_ERR_E001);
            ret.setErrorMessage(PromotionErrorConstants.COUPON_QUERY_ERR_MAP
                    .get(PromotionErrorConstants.COUPON_QUERY_ERR_E001));
            return setGsonView(ret);
        }
        try {
            ret = promotionActivityService.queryActivityDetailNew(couponRuleCode, userId,activityId);
        } catch (Exception e) {
            Object[] errArgs = { couponRuleCode,userId, e };
            LOGGER.error("queryActivityDetailNew ,查询活动详情失败，activityId:{},mobile:{},userId:{}, error:{}",
                    errArgs);
            ret.setRetFlag(ReturnMsg.FAIL);
            ret.setErrorCode(PromotionErrorConstants.COUPON_QUERY_ERR_E999);
            ret.setErrorMessage(PromotionErrorConstants.COUPON_QUERY_ERR_MAP
                    .get(PromotionErrorConstants.COUPON_QUERY_ERR_E999));
        }
        return setGsonView(ret);
    }

    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     * 
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/validActivityId.do")
    public MyGsonView validActivityId(String activityId, String activityIdSec, String activityName,
            String cityId, String endTime, String startTime, String securityKey,Integer couponResource,String storeCode, Principal principal) {
        ReturnMsg<CommonRtn> ret = new ReturnMsg<CommonRtn>();
        String userId = principal.getName();
        LOGGER.debug("开始校验促销活动, activityId=" + activityId + ",activityIdSec=" + activityIdSec
                + ", activityName=" + activityName + ", cityId=" + cityId + ",startTime="
                + startTime + ",endTime=" + endTime + "," + ",securityKey=" + securityKey
                + ",couponResource="+couponResource+",storeCode="+storeCode+",userId=" + userId);
        if (StringUtils.isEmpty(activityId) || StringUtils.isEmpty(activityIdSec)
                || StringUtils.isEmpty(activityName) || StringUtils.isEmpty(startTime)
                || StringUtils.isEmpty(endTime) || StringUtils.isEmpty(securityKey)) {
            ret.setRetFlag(ReturnMsg.FAIL);
            ret.setErrorCode(PromotionErrorConstants.VALID_ACT_ERR_E001);
            ret.setErrorMessage(PromotionErrorConstants.VALID_ACT_ERR_MAP
                    .get(PromotionErrorConstants.VALID_ACT_ERR_E001));
            return setGsonView(ret);
        }
        try{
            ret = promotionActivityService.validActivity(activityId, activityIdSec, activityName, cityId, endTime, startTime, securityKey,couponResource,storeCode,userId);
        }catch (Exception e) {
            LOGGER.error("校验促销活动异常,活动Id:"+activityId+",活动Id密文:"+activityIdSec+"工号:"+userId,e);
            ret.setRetFlag(ReturnMsg.FAIL);
            ret.setErrorCode(PromotionErrorConstants.VALID_ACT_ERR_E999);
            ret.setErrorMessage(PromotionErrorConstants.VALID_ACT_ERR_MAP
                    .get(PromotionErrorConstants.VALID_ACT_ERR_E999));
        }
        return setGsonView(ret);
    }
    
    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     * 
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/validActivityIdNew.do")
    @ResponseBody
    public ReturnMsg<CommonRtn> validActivityIdNew(ValidActivityIdReq validActivityIdReq, Principal principal) {
        ReturnMsg<CommonRtn> ret = new ReturnMsg<CommonRtn>();
        String userId = principal.getName();
        LOGGER.info(" validActivityIdNew开始校验促销活动, validActivityIdReq=" + validActivityIdReq +",userId=" + userId);
        if (validActivityIdReq == null || StringUtils.isEmpty(validActivityIdReq.getActivityId()) || StringUtils.isEmpty(validActivityIdReq.getActivityIdSec())
                || StringUtils.isEmpty(validActivityIdReq.getActivityName()) || StringUtils.isEmpty(validActivityIdReq.getStartTime())
                || StringUtils.isEmpty(validActivityIdReq.getEndTime()) || StringUtils.isEmpty(validActivityIdReq.getSecurityKey())
                || StringUtils.isEmpty(validActivityIdReq.getCouponType()) || StringUtils.isEmpty(validActivityIdReq.getCouponValue()) || StringUtils.isEmpty(validActivityIdReq.getCouponRuleCode())) {
            ret.setRetFlag(ReturnMsg.FAIL);
            ret.setErrorCode(PromotionErrorConstants.VALID_ACT_ERR_E001);
            ret.setErrorMessage(PromotionErrorConstants.VALID_ACT_ERR_MAP
                    .get(PromotionErrorConstants.VALID_ACT_ERR_E001));
            return ret;
        }
        try{
            ret = promotionActivityService.validActivityIdNew(validActivityIdReq,userId);
        }catch (Exception e) {
            LOGGER.error("validActivityIdNew 校验促销活动异常,活动Id:"+validActivityIdReq.getActivityId()+",活动Id密文:"+validActivityIdReq.getActivityIdSec()+"工号:"+userId,e);
            ret.setRetFlag(ReturnMsg.FAIL);
            ret.setErrorCode(PromotionErrorConstants.VALID_ACT_ERR_E999);
            ret.setErrorMessage(PromotionErrorConstants.VALID_ACT_ERR_MAP
                    .get(PromotionErrorConstants.VALID_ACT_ERR_E999));
        }
        return ret;
    }
    
    
    /**
     * 根据商品编码列表查询商品信息
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param activityId
     * @param couponRuleCode
     * @param principal
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryCouponByCommList.do")
    public MyGsonView queryCouponByCommList(@RequestBody CouponReq couponReq,Principal principal) {
        // 获取当前用户id，即工号
        String userId = principal.getName();
        LOGGER.info("queryCouponByCommList , 开始查询, couponReq=" + couponReq  + ",userId=" + userId);
        ReturnMsg<List<CouponCommInfo>> ret = new ReturnMsg<List<CouponCommInfo>>();
        if (couponReq == null  || StringUtils.isBlank(couponReq.getCityId())) {
            ret.setRetFlag(ReturnMsg.FAIL);
            ret.setErrorCode(PromotionErrorConstants.COUPON_QUERY_ERR_E001);
            ret.setErrorMessage(PromotionErrorConstants.COUPON_QUERY_ERR_MAP
                    .get(PromotionErrorConstants.COUPON_QUERY_ERR_E001));
            return setGsonView(ret);
        }
        try {
            ret = promotionActivityService.queryCouponByCommList(couponReq, userId);
        } catch (Exception e) {
            LOGGER.error("queryCouponByCommList , 开始查询, couponReq=" + couponReq  + ",userId=" + userId,e );
            ret.setRetFlag(ReturnMsg.FAIL);
            ret.setErrorCode(PromotionErrorConstants.COUPON_QUERY_ERR_E999);
            ret.setErrorMessage(PromotionErrorConstants.COUPON_QUERY_ERR_MAP
                    .get(PromotionErrorConstants.COUPON_QUERY_ERR_E999));
        }
        return setGsonView(ret);
    }
    
    /**
     * 根据商品查询券列表详情
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param couponReq
     * @param principal
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryCouponInfoByComm.do")
    public MyGsonView queryCouponInfoByComm(String actType,@RequestParam(value="cityId", defaultValue=PromotionConstants.PROMOTION_CITY_DEFAULT)String cityId,String commCode,String storeId,Principal principal) {
        // 获取当前用户id，即工号
        String userId = principal.getName();
        LOGGER.info("queryCouponInfoByComm , 开始查询, commCode=" + commCode  + ",actType="
        + actType + ",cityId=" + cityId + ",storeId=" + storeId + ",userId=" + userId);
        ReturnMsg<List<InnerCouponDetail>> ret = new ReturnMsg<List<InnerCouponDetail>>();
        if (StringUtils.isBlank(actType) || StringUtils.isBlank(cityId) || StringUtils.isBlank(commCode) ) {
            ret.setRetFlag(ReturnMsg.FAIL);
            ret.setErrorCode(PromotionErrorConstants.COUPON_QUERY_ERR_E001);
            ret.setErrorMessage(PromotionErrorConstants.COUPON_QUERY_ERR_MAP
                    .get(PromotionErrorConstants.COUPON_QUERY_ERR_E001));
            return setGsonView(ret);
        }
        try {
            ret = promotionActivityService.queryCouponInfoByComm(actType,cityId,commCode, storeId,userId);
        } catch (Exception e) {
            LOGGER.error("queryCouponInfoByComm , 开始查询, commCode=" + commCode  + ",actType="
        + actType + ",cityId=" + cityId + ",storeId=" + storeId + ",userId=" + userId,e );
            ret.setRetFlag(ReturnMsg.FAIL);
            ret.setErrorCode(PromotionErrorConstants.COUPON_QUERY_ERR_E999);
            ret.setErrorMessage(PromotionErrorConstants.COUPON_QUERY_ERR_MAP
                    .get(PromotionErrorConstants.COUPON_QUERY_ERR_E999));
        }
        return setGsonView(ret);
    }
    
    @RequestMapping("/synCouponRecord.do")
    @ResponseBody
    public String synCouponRecordInfo(){
        return promotionActivityService.synCouponRecord();
    }
}
